<template>
  <div id="app">
    <div id="container"></div>
    <div class="mask" v-show="maskFlag">
      <div class="back" @click="maskClose"></div>
      <div class="verifyCode">
        <input
          type="text"
          v-for="p in inputNums"
          :key="p"
          @input="inputFun($event,p)"
          :value="code[p-1]"
          :class="{success: code[p-1]}">
        <p>请输入乘客手机号码后四位，开启行程。</p>
      </div>
    </div>
    <div class="bottom">
      <div class="btn1" @click="receiving">接到乘客</div>
      <div class="btn2" @click="ArrivalsPickUp">到达上车点</div>
    </div>
  </div>
</template>
<script>
import {receiving, startJourney} from "../../api";

export default {
  name: "goPassenger",
  props: {
    inputNums: {
      type: Number,
      default: 4
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      maskFlag: false,
      lng: '',
      lat: '',
      code: this.value.split(''),
      phoneCode: '',
      order: {},
      webSocket: {}
    }
  },
  created() {
    let _this = this
    this.order = this.$store.state.order
    this.webSocket = new WebSocket('ws://192.168.137.1:8813/orderSocket/' + _this.$store.state.driverInfo.token);

    this.webSocket.onerror = function (event) {
      _this.onError(event)
    };

    this.webSocket.onopen = function (event) {
      _this.onOpen(event)
    };

    this.webSocket.onmessage = function (event) {
      _this.onMessage(event)
    };

    setInterval(() => {
      let positionPackage = {
        driverLng: _this.$store.state.driverPosition.lng,
        driverLat: _this.$store.state.driverPosition.lat
      }
      _this.webSocket.send('{"to":"' + _this.$store.state.order.passengerToken + '","msg":' + JSON.stringify(positionPackage) + '}');
    }, 5000)
  },
  mounted() {
    let _this = this
    setTimeout(function () {
      var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 12
      });

      AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：5s
          buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 30),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showCircle: false
          // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

        });
        // map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
          if(status=='complete'){
            onComplete(result)
          }else{
            onError(result)
          }
        });
      });

      //解析定位结果
      function onComplete(data) {
        console.log(data)
        _this.$store.state.driverPosition.lat = data.position.lat
        _this.$store.state.driverPosition.lng = data.position.lng
      }
      //解析定位错误信息
      function onError(data) {
        console.log("定位失败:" + data.message)
      }

      var drivingOption = {
        policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
      }

      // 构造路线导航类
      var driving = new AMap.Driving(drivingOption)

      setTimeout(() => {
        console.log("规划路线")
        // 根据起终点经纬度规划驾车导航路线
        driving.search(new AMap.LngLat(_this.$store.state.driverPosition.lng, _this.$store.state.driverPosition.lat), new AMap.LngLat(_this.order.startLongitude, _this.order.startLatitude), function(status, result) {
          // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            if (result.routes && result.routes.length) {
              // 绘制第一条路线，也可以按需求绘制其它几条路线
              drawRoute(result.routes[0])
              console.log('绘制驾车路线完成')
            }
          } else {
            console.log('获取驾车数据失败：' + result)
          }
        });

        function drawRoute (route) {
          var path = parseRouteToPath(route)

          var startMarker = new AMap.Marker({
            position: path[0],
            icon: './static/driver.png',
            map: map
          })

          var endMarker = new AMap.Marker({
            position: path[path.length - 1],
            icon: './static/passenger.png',
            map: map
          })

          var routeLine = new AMap.Polyline({
            path: path,
            isOutline: true,
            outlineColor: '#ffeeee',
            borderWeight: 2,
            strokeWeight: 5,
            strokeColor: '#18a33e',
            lineJoin: 'round'
          })

          routeLine.setMap(map)

          // 调整视野达到最佳显示区域
          map.setFitView([ startMarker, endMarker, routeLine ])
        }

        // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
        // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
        function parseRouteToPath(route) {
          var path = []

          for (var i = 0, l = route.steps.length; i < l; i++) {
            var step = route.steps[i]

            for (var j = 0, n = step.path.length; j < n; j++) {
              path.push(step.path[j])
            }
          }
          return path
        }
      }, 2000)

    }, 2000)
    let params = new URLSearchParams()
    params.append('orderNumber', _this.order.orderNumber)
    params.append('driverId', _this.$store.state.driverInfo.id)
    receiving(params)
      .then(res => {
        console.log("去接乘客成功")
      })
      .catch(err => {
        console.log("去接乘客失败");
      })
  },
  watch: {
    value(newVal){
      this.code = newVal.split('');
    },
    code(newVal){
      this.$emit('input',newVal.join(''));
    }
  },
  methods: {
    receiving: function() {
      this.maskFlag = true
    },
    maskClose: function() {
      this.maskFlag = false
    },
    //1.监听用的键入，每次键入都替换掉焦点输入框的值
    //2.输入框的值只能有一位
    inputFun(e,p){
      let _this = this
      let ele = e.target;
      let siblingsNode = ele.parentNode.children;
      if(!e.data){//删除
        this.$delete(this.code,p-1);
        if(p <= 2){//边界值
          p = 2;
        }
        siblingsNode[p-2].focus();
        return false;
      }
      let value = e.target.value.replace(/\W/g,'').slice(-1);
      ele.value = value;
      this.$set(this.code,p-1,value)
      if(p >= siblingsNode.length-1){//边界值
        p = siblingsNode.length-1;
      }
      if(value){//上一个元素获得焦点
        siblingsNode[p].focus();
      }
      this.phoneCode += value
      let lastPhoneCode = this.order.passengerPhone.slice(this.order.passengerPhone.length - 4, this.order.passengerPhone.length)
      if (this.phoneCode === lastPhoneCode) {
        let params = new URLSearchParams()
        params.append('orderNumber', _this.order.orderNumber)
        params.append('driverId', _this.$store.state.driverInfo.id)
        params.append('phone', _this.$store.state.driverInfo.phone)
        params.append('receivePassengerLongitude', _this.$store.state.driverPosition.lng)
        params.append('receivePassengerLatitude', _this.$store.state.driverPosition.lat)
        startJourney(params)
        .then(res => {
          if (res.result === true) {
            console.log("接到乘客成功")
            let positionPackage = {
              orderNumber: _this.$store.state.order.orderNumber,
            }
            _this.webSocket.send('{"to":"' + _this.$store.state.order.passengerToken + '","msg":' + JSON.stringify(positionPackage) + '}');
            _this.$router.push({path:'/driver/startJourney'})
          }
        })
        .catch(err => {
          console.log("接到乘客失败")
        })
      }
    },
    onMessage(event) {
      let _this = this
      var msg = JSON.parse(event.data)
      if (msg && msg.ping && msg.ping != '') {
      } else {
        // msg.msg.flag = false
        console.log(msg.msg)
      }
    },
    onOpen(event) {
      console.log('Connection established')
    },
    onError(event) {
      alert(event.data);
    },
    ArrivalsPickUp: function () {
      let _this = this
      _this.$store.state.driverPosition.lng = _this.order.startLongitude
      _this.$store.state.driverPosition.lat = _this.order.startLatitude
    }
  },
  destroyed() {
    this.webSocket.close()
  },
}
</script>

<style scoped>
.mask{
  z-index: 999;
  position: fixed;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: #FFF;
}
.mask .back{
  margin-top: 15px;
  margin-left: 15px;
  width: 40px;
  height: 40px;
  border-radius: 40px;
  background-color: #CCC;
}
  .bottom{
    z-index: 200;
    width: 100%;
    height: 130px;
    background-color: #FFF;
    position: fixed;
    bottom: 0px;
    box-shadow: 0 0px 15px rgba(0,0,0,.2);
  }
  .btn1{
    position: relative;
    top: 20px;
    margin: 0 auto;
    width: 80%;
    height: 40px;
    border-radius: 20px;
    background-color: #ff6f1c;
    color: #FFF;
    line-height: 38px;
    box-shadow: 0 0px 15px rgba(0,0,0,.3);
  }
  .btn2{
    position: relative;
    top: 30px;
    margin: 0 auto;
    width: 80%;
    height: 40px;
    border-radius: 20px;
    background-color: #666;
    color: #FFF;
    line-height: 38px;
    box-shadow: 0 0px 15px rgba(0,0,0,.3);
  }
  .verifyCode{
    margin-top: 100px;
  }
  .verifyCode input{
    font-size: 14px;
    margin-right: 8px;
    width: 60px;
    height: 60px;
    border-radius: 5px;
    text-align: center;
    border-color: #999;
    outline: none;
  }
.verifyCode input:focus{
  border-color: #333;
}
  .verifyCode p {
    margin-left: -35px;
    margin-top: 10px;
    font-size: 14px;
    color: #bfbbbb;
  }
</style>
